package com.mail.tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class Util {
	
	static Connection c;
	
	
	public static List find(String sql) throws SQLException {
		List list = new ArrayList();
		if (c == null || c.isClosed()) {
			c = myOracle.getDataSource().getConnection();
		}
		PreparedStatement ps = c.prepareStatement(sql);
		LOG.out(sql);
		ResultSet rs = ps.executeQuery();
		int col = rs.getMetaData().getColumnCount();
		while (rs.next()) {
			Object obj[] = new Object[col];
			for (int i = 1; i <= col; i++) {
				obj[i - 1] = rs.getObject(i);
			}
			list.add(obj);
		}
		ps.close();
		return list;
	}

	public static List findByName(String sql) throws SQLException {
		List list = new ArrayList();
		if (c == null || c.isClosed()) {
			c = myOracle.getDataSource().getConnection();
		}
		PreparedStatement ps = c.prepareStatement(sql);
		LOG.out(sql);
		ResultSet rs = ps.executeQuery();
		int col = rs.getMetaData().getColumnCount();
		Object o[] = new Object[col];
		for(int i = 1;i<col+1;i++){
			o[i-1] = rs.getMetaData().getColumnLabel(i);
		}
		list.add(o);
		while (rs.next()) {
			Object obj[] = new Object[col];
			for (int i = 1; i <= col; i++) {
				obj[i - 1] = rs.getObject(i);
			}
			list.add(obj);
		}
		ps.close();
		return list;
	}
	// yyyy-MM-dd HH:mm:ss
	public static String getDateTime(String format) {
		String str = "";
		// Calendar cal = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		str = formatter.format(new Date().getTime());
		return str;
	}
	
	public static String getDateTimeBySome(String format,int p){
		Calendar   cal   =   Calendar.getInstance(); 
		cal.add(Calendar.DATE,   p); 
		String str   =   new   SimpleDateFormat( format).format(cal.getTime());
		return str;
	}

	public static String killLeftZero(String src) {
		if (src.startsWith("0")) {
			int p = 0;
			for (int i = 0; i < src.length(); i++) {
				if (src.charAt(i) != '0') {
					p = i;
					break;
				}
			}
			return src.substring(p);
		} else
			return src;
	}

	public static String clearString(String msg) {
		if (msg == null)
			return null;
		int p = 0;
		char[] c = msg.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 0) {
				p = i;
				break;
			}
		}
		return new String(c, 0, p);
	}

	public static String clearByte(byte[] b) {
		String tmp = "";
		int p = 0;
		for (int i = 0; i < b.length; i++) {
			if (b[i] == 0) {
				p = i;
				break;
			}
		}
		tmp = new String(b, 0, p);
		return tmp;
	}

	public static String left_(String src, String split, int length) {
		String tmp = "";
		try {
			for (int i = 0; i < length - src.getBytes("gb2312").length; i++) {
				tmp += split;
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return tmp + src;
	}

	public static String right_(String src, String split, int length) {
		String tmp = "";
		try {
			for (int i = 0; i < length - src.getBytes("gb2312").length; i++) {
				tmp += split;
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return src + tmp;
	}

	// type=1 有回包 0 无

	public static byte[] appendByte(byte[] src, byte[] n) {
		if (src == null)
			return n;
		byte[] tmp = new byte[src.length + n.length];
		System.arraycopy(src, 0, tmp, 0, src.length);
		System.arraycopy(n, 0, tmp, src.length, n.length);
		return tmp;
	}

	public static String getCurrentDate(String format) {
		SimpleDateFormat f = new SimpleDateFormat(format);
		Date d = new Date();

		return f.format(d);
	}

	public static byte[] subByte(byte[] src, int start, int end) {
		byte[] tmp = new byte[end - start];
		int k = 0;
		for (int i = start; i < end; i++) {
			tmp[k] = src[i];
			k++;
		}
		return tmp;
	}

	public static String addZero(String old, int num) {
		String str = "";
		if (old == null || old.equals("")) {
			old = "";
		}
		if (old.length() > num) {
			return old;
		}
		for (int i = 0; i < num - old.length(); i++) {
			str += "0";
		}
		str = str + old;
		return str;
	}

	public static String moveRightTwo(String str) {

		// str = Float.valueOf(str)+"";

		if (str == null) {
			str = "0";
		}
		if (str.equals("")) {
			return "0";
		}
		if (str.indexOf(".") != -1) {
			if (str.endsWith("\\.")) {
				return str.substring(0, str.length() - 1) + "00";
			}
			String tmp[] = str.split("\\.");
			if (tmp[1].length() == 1) {
				return tmp[0] + tmp[1] + "0";
			}
			if (tmp[1].length() == 2) {
				return tmp[0] + tmp[1];
			}
			if (tmp[1].length() > 2) {
				return tmp[0] + tmp[1].substring(0, 2);
			}

		} else {
			return str + "00";
		}
		return "";
	}

	public static String moveLeftTwo(String str) {

		// str = Float.valueOf(str)+"";
		if (str == null) {
			str = "0";
		}
		if (str.equals("")) {
			return "0";
		}
		if (str.indexOf(".") == -1) {
			str = str + ".";
		}
		if (str.indexOf(".") == 1)
			return "0.0" + str.replace(".", "");
		char tmp[] = str.toCharArray();
		String s = "";
		for (int i = 0; i < tmp.length; i++) {
			if (str.indexOf(".") - 2 == i) {
				s += ".";
			}
			if (tmp[i] != '.')
				s += tmp[i];
		}
		return s;
	}

	public static String getAMT(String old) {

		if (old == null) {
			old = "";
		}
		String tmp = "";
		for (int i = old.length(); i < 12; i++) {
			tmp += "0";
		}
		old = tmp + old;
		return old;
	}

	public static String getFEE(String old) {

		if (old == null) {
			old = "";
		}
		String tmp = "";
		for (int i = old.length(); i < 8; i++) {
			tmp += "0";
		}
		old = tmp + old;
		return old;
	}

	public static String FormatSum(String sum) {
		if (sum == null) {
			return "";
		}
		if (sum.equals("") || sum.equals("0") || sum.equals("-")) {
			return "0";
		}
		String m = "";
		if (sum.startsWith("-")) {
			m = "-";
			sum = sum.replace("-", "");
		}
		// System.out.println("sum" + sum);
		sum = "00" + sum.trim();
		// System.out.println("sum" + sum);
		String sum2 = "." + sum.substring(sum.length() - 2, sum.length());
		String sum1 = KillZero(sum.substring(0, sum.length() - 2));
		sum1 += sum2;
		if (sum1.startsWith(".")) {
			sum1 = "0" + sum1;
		}
		return m + sum1;
	}

	public static String KillZero(String sum) {
		String temp = "";
		for (int i = 0; i < sum.length(); i++) {
			if (sum.charAt(i) != '0' || i == sum.length() - 1) {
				temp = sum.substring(i, sum.length());
				break;
			}
		}
		return temp;
	}

	public static void saveToFile(String path, String msg) throws Exception {
		File file = new File(path);
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(msg.getBytes("GBK"));
		fos.flush();
		fos.close();
	}
	
	public static void saveToExcelFile(String path,List l) throws Exception{
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("new sheet");
		HSSFRow row = null;
		HSSFCell cell = null;
		short rowNum = 0;
		for (int i = 0; i < l.size(); i++) {
			row = sheet.createRow((short) rowNum);
			Object[] obj = (Object[]) l.get(i);
			for (int p = 0; p < obj.length; p++) {
				cell = row.createCell((short) p);
				cell.setEncoding(HSSFCell.ENCODING_UTF_16);
				cell.setCellValue(obj[p]+"");
			}
			rowNum++;
		}
		File file = new File(path);
		FileOutputStream fos = new FileOutputStream(file);
		wb.write(fos);
		fos.flush();
		fos.close();
	}

	public static String readByFile(String path) throws Exception {
		String msg = "";
		File file = new File(path);
		FileInputStream fis = new FileInputStream(file);
		byte[] tmp = new byte[fis.available()];
		fis.read(tmp);
		msg = new String(tmp);
		return msg;
	}

	public static String addSpace(String src, int length) {
		if (src == null)
			src = "";
		String tmp = "";
		for (int i = 0; i < length - src.length(); i++) {
			tmp += " ";
		}
		return src + tmp;
	}

	public static String numtochinese(String input) {
		String s1 = "零壹贰叁肆伍陆柒捌玖";
		String s4 = "分角整元拾佰仟万拾佰仟亿拾佰仟";
		String temp = "";
		String result = "";
		if (input == null)
			return "输入字串不是数字串只能包括以下字符（′0′～′9′，′.′)，输入字串最大只能精确到仟亿，小数点只能两位！";
		temp = input.trim();
		float f;
		try {
			f = Float.parseFloat(temp);

		} catch (Exception e) {
			return "输入字串不是数字串只能包括以下字符（′0′～′9′，′.′)，输入字串最大只能精确到仟亿，小数点只能两位！";
		}
		int len = 0;
		if (temp.indexOf(".") == -1)
			len = temp.length();
		else
			len = temp.indexOf(".");
		if (len > s4.length() - 3)
			return ("输入字串最大只能精确到仟亿，小数点只能两位！");
		int n1, n2 = 0;
		String num = "";
		String unit = "";

		for (int i = 0; i < temp.length(); i++) {
			if (i > len + 2) {
				break;
			}
			if (i == len) {
				continue;
			}
			n1 = Integer.parseInt(String.valueOf(temp.charAt(i)));
			num = s1.substring(n1, n1 + 1);
			n1 = len - i + 2;
			unit = s4.substring(n1, n1 + 1);
			result = result.concat(num).concat(unit);
		}
		if ((len == temp.length()) || (len == temp.length() - 1))
			result = result.concat("整");
		if (len == temp.length() - 2)
			result = result.concat("零分");
		return result;
	}

	public static int getDayByMouth(String mouth) {
		mouth = mouth + "01";
		int i = 0;
		Date date = new Date();
		DateFormat format = new SimpleDateFormat("yyyyMMdd");
		try {
			date = format.parse(mouth);
			while (true) {
				String strDate = format.format(date);
				i++;

				if (strDate.substring(6).equals("01") && !strDate.equals(mouth)) {
					break;
				}
				Calendar theCa = Calendar.getInstance();
				theCa.setTime(date);
				theCa.add(Calendar.DATE, 1);
				date = theCa.getTime();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return i - 1;
	}

	public static String toHexString(byte b) {
		String s = Integer.toHexString(b & 0xFF);
		if (s.length() == 1) {
			return "0" + s;
		} else {
			return s;
		}
	}

	public static String getNextDateTime(int nextday, String format) {
		String str = "";
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, nextday);
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		str = formatter.format(cal.getTime());
		return str;
	}

	public static String getBatchID() {
		String str = "";
		Random random = new Random();
		int id = random.nextInt(99999999);
		str += Util.left_(id + "", "0", 8);
		return str;
	}

	public static void main(String args[]) {

	}
}
